/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.max.oti.system.bean.sppp;

import com.max.oti.datetime.MDifferenceDate;
import com.max.oti.system.bean.IndexLoginBean;
import com.max.oti.system.model.AmplificationPractice;
import com.max.oti.system.model.Company;
import com.max.oti.system.model.HistoryPractice;
import com.max.oti.system.model.Practice;
import com.max.oti.system.service.interfac.IAdviserPracticeService;
import com.max.oti.system.service.interfac.IAmplificationPracticeService;
import com.max.oti.system.service.interfac.ICompanyService;
import com.max.oti.system.service.interfac.IHistoryPracticeService;
import com.max.oti.system.service.interfac.IPracticeService;
import com.max.oti.system.util.Clazz;
import com.max.oti.system.util.FacesUtil;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;

/**
 *
 * @author Alberto
 */
@ManagedBean
@SessionScoped
public class PracticeBean implements Serializable {

    @ManagedProperty("#{practiceService}")
    IPracticeService practiceService;
    @ManagedProperty("#{companyService}")
    ICompanyService companyService;
    @ManagedProperty("#{clazz}")
    Clazz clazz;
    @ManagedProperty("#{adviserPracticeService}")
    IAdviserPracticeService adviserPracticeService;
    @ManagedProperty("#{historyPracticeService}")
    IHistoryPracticeService historyPracticeService;
    @ManagedProperty("#{amplificationPracticeService}")
    IAmplificationPracticeService amplificationPracticeService;
    @ManagedProperty("#{indexLoginBean}")
    IndexLoginBean indexLoginBean;
    ////////////////////////////////////////////////////////////////////////
    private Practice practice = new Practice();
    private List<Company> listCompany;
    private List<HistoryPractice> listHistoryPracticeNoRepeat;
    private List<String> listStateString;
    ///////////////////FILTERING///////////////////////
    private String filterValue;
    private String filterCombo;
    /////////////////////CUANTOS MESE DE AMPLIFICACION/////////////7
    private Integer months;
    private String movitveAmplification;

    public void initCollection() {
        try {
            indexLoginBean.setNavigation("./content/practice.xhtml");
            //"lower(doc.name) like '%cats%'"
            String HQL = "select p.id as id, p.idPractice as idPractice, p.oldHistory as oldHistory, p.idState as idState "
                    + "from HistoryPractice p where p.oldHistory is false";
            listHistoryPracticeNoRepeat = historyPracticeService.listHQL(HQL, HistoryPractice.class);

            practice = new Practice();
        } catch (Exception ex) {
            Logger.getLogger(PracticeBean.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    public List<String> getListStateString() {
        if (listStateString == null) {
            listStateString = new ArrayList<String>();
            listStateString.add(Clazz.STATE.Name.INSCRIPCION_DE_PRACTICAS);
            listStateString.add(Clazz.STATE.Name.ASIGNACION_DE_ASESOR_Y_RESOLUCION);
            listStateString.add(Clazz.STATE.Name.SUPERVISION);
            listStateString.add(Clazz.STATE.Name.ANULACION_POR_SUPERVICION);
            listStateString.add(Clazz.STATE.Name.AMPLIACION);
            listStateString.add(Clazz.STATE.Name.ENTREGA_DE_INFORME);
            listStateString.add(Clazz.STATE.Name.ANULACION_POR_ENTREGA_DE_INFORME_FUERA_DE_FECHA);
            listStateString.add(Clazz.STATE.Name.PARA_SUSTENTAR);
            listStateString.add(Clazz.STATE.Name.APROVADO);
            listStateString.add(Clazz.STATE.Name.DESAPROVADO);
            listStateString.add(Clazz.STATE.Name.DESAPROVADO_CON_CORRECION);
            listStateString.add(Clazz.STATE.Name.PRACTICA_CULMINADA);
        }
        return listStateString;
    }

    public void verifiAmplification() {
        //if(practice.getAmplificationPracticeList().isEmpty())
        System.out.println("Tiene : " + practice.getAmplificationPracticeList().size() + " Ampliaciones");
        System.out.println("star " + practice.getStartDate());
        System.out.println("end " + practice.getDateFinal());
        MDifferenceDate.differenceDates(practice.getStartDate(), practice.getEndDate());
        System.out.println("Resta Meses: " + MDifferenceDate.getMoths());
        if (MDifferenceDate.getMoths() < 6 && practice.getAmplificationPracticeList().size() < 2) {
            FacesUtil.addMessage("Puede extender sus practicas", null, FacesMessage.SEVERITY_INFO);
        }
    }

    public void saveAmplification() {
        MDifferenceDate.differenceDates(practice.getStartDate(), practice.getEndDate());
        int totalMonths = MDifferenceDate.getMoths() + months;
        if (totalMonths < 6) {
            //INSERTAR Y VERIFICAR SI ES LA SEGUNDA VEZ QUE PIDE AMPLIACION
            if (practice.getAmplificationPracticeList().isEmpty()) {
                try {
                    AmplificationPractice ap = new AmplificationPractice();
                    ap.setIdPractice(practice);
                    ap.setMotive(this.movitveAmplification);
                    Date d = new Date();
                    d.setDate(practice.getEndDate().getDate());
                    d.setYear(practice.getEndDate().getYear());
                    d.setMonth(practice.getEndDate().getMonth() + months);
                    ap.setNewDate(d);
                    System.out.println(amplificationPracticeService);
                    amplificationPracticeService.save(ap);
                    String strD = (d.getYear() + 1900) + "-" + (d.getMonth() + 1) + "-" + d.getDate();
                    practiceService.HQLexecute("update Practice c set c.endDate='" + strD + "' where c.id=" + practice.getId());
                } catch (Exception ex) {
                    Logger.getLogger(PracticeBean.class.getName()).log(Level.SEVERE, null, ex);
                }
            } else if (practice.getAmplificationPracticeList().size() == 1) {
                try {
                    //ACTUALIZAR PRACTICE e INSERTAR A LA BASE D DATOS
                    AmplificationPractice ap = new AmplificationPractice();
                    ap.setIdPractice(practice);
                    ap.setMotive("Ampliación de practicas");
                    Date d = new Date();
                    d.setDate(practice.getEndDate().getDate());
                    d.setYear(practice.getEndDate().getYear());
                    d.setMonth(practice.getEndDate().getMonth() + months);
                    ap.setNewDate(d);
                    amplificationPracticeService.save(ap);
                    String strD = (d.getYear() + 1900) + "-" + (d.getMonth() + 1) + "-" + d.getDate();
                    practiceService.HQLexecute("update Practice c set c.endDate='" + strD + "' where c.id=" + practice.getId());
                    practiceService.HQLexecute("update Practice c set c.amplificated='true' where c.id=" + practice.getId());

                } catch (Exception ex) {
                    Logger.getLogger(PracticeBean.class.getName()).log(Level.SEVERE, null, ex);
                }
            }

            this.chargeDataTable();
            FacesUtil.getRequestContext().update("formTablePracticeId");
        } else if (totalMonths == 6) {
            try {
                //ACTUALIZAR PRACTICE e INSERTAR A LA BASE D DATOS
                AmplificationPractice ap = new AmplificationPractice();
                ap.setIdPractice(practice);
                ap.setMotive("Ampliación de practicas");
                Date d = new Date();
                d.setDate(practice.getEndDate().getDate());
                d.setYear(practice.getEndDate().getYear());
                d.setMonth(practice.getEndDate().getMonth() + months);
                ap.setNewDate(d);
                amplificationPracticeService.save(ap);
                String strD = (d.getYear() + 1900) + "-" + (d.getMonth() + 1) + "-" + d.getDate();
                practiceService.HQLexecute("update Practice c set c.endDate='" + strD + "' where c.id=" + practice.getId());
                practiceService.HQLexecute("update Practice c set c.amplificated='true' where c.id=" + practice.getId());
                this.chargeDataTable();
                FacesUtil.getRequestContext().update("formTablePracticeId");
            } catch (Exception ex) {
                Logger.getLogger(PracticeBean.class.getName()).log(Level.SEVERE, null, ex);
            }
        } else if (totalMonths > 6) {
            FacesUtil.addMessage("No puede exceder de 6 meses: REGALMENTO :", null, FacesMessage.SEVERITY_INFO);
        }
    }

    public void chargeDataTable() {
        try {
            String HQL = "select p.id as id, p.idPractice as idPractice, p.oldHistory as oldHistory, p.idState as idState "
                    + "from HistoryPractice p where p.oldHistory is false";
            listHistoryPracticeNoRepeat = historyPracticeService.listHQL(HQL, HistoryPractice.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
//        List<Criterion> listCriterion = new ArrayList<Criterion>();
//        listCriterion.add(Restrictions.eq("oldHistory", false));
//        listHistoryPracticeNoRepeat = historyPracticeService.listCriterion(listCriterion);
    }
    //SE ENVIA ESTE VALOR A LA OTRA VISTA

    public Practice setSendPractice(Practice practice) {
        Practice praTemp = null;
        try {
            praTemp = practiceService.getById(practice.getId());
        } catch (Exception ex) {
            Logger.getLogger(PracticeBean.class.getName()).log(Level.SEVERE, null, ex);
        }
        return praTemp;
    }

    //SE ENVIA A LA OTRA VISTA ESTE VALOR
    public Practice editPractice(Integer idPractice) {
        try {
            return practiceService.load(idPractice);
        } catch (Exception ex) {
            Logger.getLogger(PracticeBean.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }

    //FILTRADO PARA LOS CODIGOS
    public void filterTablePractice() {
        System.out.println("Filtrando");
        if (filterValue == null) {
            filterValue = "";
        }
        String HQL = "select p.id as id, p.idPractice as idPractice, p.oldHistory as oldHistory, p.idState as idState "
                + "from HistoryPractice p where p.oldHistory is false "
                + "and lower(p.idPractice.codeAlumn) like '%(busqueda)%'";
        if (filterCombo != null && !filterCombo.equals("TODOS")) {
            HQL = "select p.id as id, p.idPractice as idPractice, p.oldHistory as oldHistory, p.idState as idState "
                    + "from HistoryPractice p where p.oldHistory is false "
                    + "and lower(p.idPractice.codeAlumn) like '%(busqueda)%' and "
                    + "p.idState.name='(stateName)'";
            HQL = HQL.replace("(stateName)", filterCombo);
        }

        HQL = HQL.replace("(busqueda)", filterValue.toLowerCase());
        try {
            listHistoryPracticeNoRepeat = historyPracticeService.listHQL(HQL, HistoryPractice.class);
            FacesUtil.addMessage("Para ver todos debe borrar y buscar nuevamente", null, FacesMessage.SEVERITY_INFO);
            FacesUtil.getRequestContext().update("formTablePracticeId");
        } catch (Exception e) {
            System.out.println(e.getMessage());
            e.printStackTrace();
        }


    }

//<editor-fold defaultstate="collapsed" desc="Getter and Setter">
    public Practice getPractice() {
        return practice;
    }

    public IndexLoginBean getIndexLoginBean() {
        return indexLoginBean;
    }

    public void setIndexLoginBean(IndexLoginBean indexLoginBean) {
        this.indexLoginBean = indexLoginBean;
    }

    public String getMovitveAmplification() {
        return movitveAmplification;
    }

    public String getFilterCombo() {
        return filterCombo;
    }

    public void setFilterCombo(String filterCombo) {
        this.filterCombo = filterCombo;
    }

    public void setMovitveAmplification(String movitveAmplification) {
        this.movitveAmplification = movitveAmplification;
    }

    public String getFilterValue() {
        return filterValue;
    }

    public void setFilterValue(String filterValue) {
        this.filterValue = filterValue;
    }

    public void setPractice(Practice practice) {
        this.practice = practice;
    }

    public Integer getMonths() {
        return months;
    }

    public void setMonths(Integer months) {
        this.months = months;
    }

    public List<Company> getListCompany() {
        return listCompany;
    }

    public void setListCompany(List<Company> listCompany) {
        this.listCompany = listCompany;
    }

    public void setPracticeService(IPracticeService practiceService) {
        this.practiceService = practiceService;
    }

    public void setCompanyService(ICompanyService companyService) {
        this.companyService = companyService;
    }

    public void setClazz(Clazz clazz) {
        this.clazz = clazz;
    }

    public void setAmplificationPracticeService(IAmplificationPracticeService amplificationPracticeService) {
        this.amplificationPracticeService = amplificationPracticeService;
    }

    public void setAdviserPracticeService(IAdviserPracticeService adviserPracticeService) {
        this.adviserPracticeService = adviserPracticeService;
    }

    public void setHistoryPracticeService(IHistoryPracticeService historyPracticeService) {
        this.historyPracticeService = historyPracticeService;
    }

    public List<HistoryPractice> getListHistoryPracticeNoRepeat() {
        return listHistoryPracticeNoRepeat;
    }

    public void setListHistoryPracticeNoRepeat(List<HistoryPractice> listHistoryPracticeNoRepeat) {
        this.listHistoryPracticeNoRepeat = listHistoryPracticeNoRepeat;
    }
//</editor-fold>
}
